// 检查登录状态 - 只检查token和过期时间
export const checkLogin = async () => {
  try {
    const token = uni.getStorageSync('auth_token')
    const tokenExpire = uni.getStorageSync('token_expire')
    
    if (token && tokenExpire && Date.now() < tokenExpire) {
      return { isLogged: true }
    }
    
    return { isLogged: false }
  } catch (error) {
    console.error('检查登录状态错误:', error)
    return { isLogged: false, error }
  }
}

// 微信登录函数 - 只存储token和过期时间
export const wechatLogin = () => {
  return new Promise((resolve, reject) => {
    // 调用微信登录接口
    uni.login({
      provider: 'weixin',
      success: (loginRes) => {
        if (loginRes.code) {
          console.log('微信登录获取code成功:', loginRes.code);
          
          // 实际调用后端API
          uni.request({
            url: 'http://localhost:9999/auth/wechat-login',
            method: 'POST',
            data: {
              code: loginRes.code
            },
            success: (res) => {
              if (res.data && res.data.success) {
                const { token, expiresIn } = res.data.data;
                const tokenExpire = Date.now() + expiresIn * 1000;
                
                // 保存登录状态 - 只存储token和过期时间
                uni.setStorageSync('auth_token', token);
                uni.setStorageSync('token_expire', tokenExpire);
                
                resolve({ token, expiresIn });
              } else {
                reject(new Error(res.data.message || '登录失败'));
              }
            },
            fail: (err) => {
              reject(new Error('网络请求失败: ' + JSON.stringify(err)));
            }
          });
        } else {
          reject(new Error('获取微信code失败: ' + loginRes.errMsg));
        }
      },
      fail: (err) => {
        reject(new Error('微信登录失败: ' + JSON.stringify(err)));
      }
    });
  });
}

// 移除getUserInfo函数，因为不再存储用户信息

// 获取认证token
export const getAuthToken = () => {
  return uni.getStorageSync('auth_token') || null
}

// 清除登录状态 - 移除user_info相关存储
export const clearLoginStatus = () => {
  uni.removeStorageSync('auth_token')
  uni.removeStorageSync('token_expire')
}

// 请求拦截器，自动添加token
export const requestWithAuth = (options) => {
  const token = getAuthToken()
  if (token) {
    options.header = options.header || {}
    options.header['Authorization'] = `Bearer ${token}`
  }
  
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        // 检查token是否过期
        if (res.statusCode === 401) {
          clearLoginStatus()
          uni.$emit('tokenExpired')
        }
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}